package fr.charlott.view;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import fr.charlott.business.dto.CategorieDTO;
import fr.charlott.business.service.CategorieService;
import fr.charlott.tools.exceptions.FunctionalException;
import fr.charlott.tools.exceptions.TechnicalException;

@Component("nouvelleCategorieControler")
@Scope("view")
public class NouvelleCategorieControler extends CharlottControler {

    private static final long serialVersionUID = -6404906491610002771L;

    public static final String EDITED_CATEGORIE = "editedCategorie";

    /**
     * Service
     */
    private CategorieService categorieService;

    private CategorieDTO categorie;

    public NouvelleCategorieControler() {
        super();
    }

    @Autowired(required = true)
    public NouvelleCategorieControler(CategorieService categorieService, ApplicationControler applicationControler) {
        super();
        this.categorieService = categorieService;

        // Recupere la personne selectionnee dans la session
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        categorie = (CategorieDTO) externalContext.getSessionMap().get(EDITED_CATEGORIE);

        if (categorie == null) {
            categorie = new CategorieDTO();
        }
    }

    // navigation

    public String ajouterCategorie() throws TechnicalException, FunctionalException {
        try {
            categorieService.ajouterCategorie(categorie);
            cleanSession(EDITED_CATEGORIE);
            return "gestionCategories";
        } catch (TechnicalException e) {
            FacesMessage msg = new FacesMessage("Error", e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
    }

    public String annuler() {
        cleanSession(EDITED_CATEGORIE);
        return "gestionCategories";
    }

    // getters / setters

    public CategorieDTO getCategorie() {
        return categorie;
    }
}